<template>
  <div id="GlobalHeader">
    <a-menu
      mode="horizontal"
      :selected-keys="selectKeys"
      @menu-item-click="doClick"
    >
      <img src="../assets/logoIco.png" class="img_style" />
      <a-menu-item v-for="item in visibleRoutes" :key="item.path">
        {{ item.name }}
      </a-menu-item>

      <div class="userName">
        {{ store.state.user?.loginUser?.userName ?? '未登录' }}
        <!-- 如果存在该值，返回该值，否则返回未登录-->
      </div>
    </a-menu>
  </div>
</template>

<script setup lang="ts">
import routes from '@/router/routes'
import { useRoute, useRouter } from 'vue-router'
import { ref, computed } from 'vue'
import { useStore } from 'vuex'
import checkAccess from '@/access/checkAccess'
import ACCESS_ENUM from '@/access/accessEnum'

const router = useRouter()
//默认主页
const selectKeys = ref(['/'])

// 展示在菜单的路由数组，需要延迟加载
const visibleRoutes = computed(() => {
  return routes.filter((item, index) => {
    if (item.meta?.hideInMenu) {
      return false
    }
    // 根据权限过滤菜单
    if (
      !checkAccess(store.state.user.loginUser, item?.meta?.access as string)
    ) {
      return false
    }
    return true
  })
})

//路由跳转后，更新选中的菜单项
router.afterEach((to, from, failure) => {
  selectKeys.value = [to.path]
})

//点击按钮触发事件
const doClick = (key: string) => {
  router.push({
    path: key
  })
}

//延迟1ms执行
setTimeout(() => {
  store.dispatch('user/getLoginUser')
}, 1)

const store = useStore()
console.log(store.state.user.loginUser.userName)
</script>

<style scoped>
#GlobalHeader {
}

.img_style {
  margin-right: 70px;
}

.userName {
  float: right;
  margin-top: 25px;
}
</style>
